package com.xindacloud.sms.console.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindacloud.sms.console.result.Result;
import com.xindacloud.sms.console.result.ResultGenerator;
import com.xindacloud.sms.console.system.dto.ProjectMemberDTO;
import com.xindacloud.sms.console.system.dto.QueryProjectListDTO;
import com.xindacloud.sms.console.system.dto.SaveSmsProjectDTO;
import com.xindacloud.sms.console.system.entity.SmsProject;
import com.xindacloud.sms.console.system.entity.SmsProjectMember;
import com.xindacloud.sms.console.system.entity.SmsUser;
import com.xindacloud.sms.console.system.mapper.SmsProjectMapper;
import com.xindacloud.sms.console.system.service.ISmsProjectMemberService;
import com.xindacloud.sms.console.system.service.ISmsProjectService;
import com.xindacloud.sms.console.system.service.ISmsUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 短信项目 服务实现类
 * </p>
 *
 * @author czc
 * @since 2019-10-08
 */
@Service
@Slf4j
public class SmsProjectServiceImpl extends ServiceImpl<SmsProjectMapper, SmsProject> implements ISmsProjectService {


    @Autowired
    private ISmsProjectMemberService smsProjectMemberService;
    @Autowired
    private ISmsUserService smsUserService;

    @Override
    public Result getSmsProjectList(QueryProjectListDTO queryProjectListDTO) {
        IPage<SmsProject> page = new Page<>(queryProjectListDTO.getPageNum(), queryProjectListDTO.getPageSize());
        QueryWrapper<SmsProject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_user_id", queryProjectListDTO.getCreateUserId());
        queryWrapper.like(StringUtils.isNotEmpty(queryProjectListDTO.getSmsProjectName()),
                "sms_project_name", queryProjectListDTO.getSmsProjectName());
        queryWrapper.eq(StringUtils.isNotEmpty(queryProjectListDTO.getChannelType()),
                "channel_type", queryProjectListDTO.getChannelType());
        final IPage<SmsProject> projectIPage = this.page(page, queryWrapper);

        projectIPage.getRecords().stream()
                .peek(rs -> {
                    final List<ProjectMemberDTO> projectMemberList = getProjectMemberList(rs.getProjectId());
                    rs.setProjectMembersList(CollectionUtils.isNotEmpty(projectMemberList) ? projectMemberList : Collections.emptyList());
                }).collect(Collectors.toList());
        return ResultGenerator.genSuccessResult(projectIPage);
    }

  /*  @Override
    public Result<SmsProject> saveOrUpdateSmsProject(SmsProjectDTO smsProjectDTO) {
        SmsProject smsProject = new SmsProject();
        try {
            BeanUtils.copyProperties(smsProjectDTO, smsProject);
            smsProject.setToken(getUUIDString());
            smsProject.setPassword(getUUIDString());
        } catch (BeansException e) {
            log.error(e.getMessage(), e);
        }
        if (this.saveOrUpdate(smsProject)) {
            return new Result<>(smsProject, HttpStatus.OK);
        } else {
            return new Result<>(smsProject, HttpStatus.BAD_REQUEST);
        }
    }*/

    private String getUUIDString() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    @Override
    public Result deleteSmsProject(String projectId) {
        if (this.removeById(projectId)) {
            return ResultGenerator.genSuccessResult("删除成功！");
        } else {
            return ResultGenerator.genClientFailResult("删除失败！");
        }
    }


    @Override
    public SmsProject saveSmsProject(SaveSmsProjectDTO saveSmsProjectDTO) {

        SmsProject smsProject = new SmsProject();
        try {
            BeanUtils.copyProperties(saveSmsProjectDTO, smsProject);
            //smsProject.setToken(getUUIDString());
            //smsProject.setPassword(getUUIDString());
            if (this.save(smsProject)) {
                return smsProject;
            }
        } catch (BeansException e) {
            log.error(e.getMessage(), e);
        }

        return null;
    }

    @Override
    public SmsProject updateSmsProject(SaveSmsProjectDTO updateProjectDTO) {
        SmsProject smsProject = new SmsProject();
        try {
            BeanUtils.copyProperties(updateProjectDTO, smsProject);
            if (this.updateById(smsProject)) {
                return smsProject;
            }
        } catch (BeansException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private List<ProjectMemberDTO> getProjectMemberList(String projectId) {
        final List<SmsProjectMember> smsProjectMembers = smsProjectMemberService.querySmsProjectMemberList(projectId);
        if (CollectionUtils.isNotEmpty(smsProjectMembers)) {
            final List<Integer> ids = smsProjectMembers.stream()
                    .map(SmsProjectMember::getUserId)
                    .collect(Collectors.toList());
            final List<SmsUser> smsUsers = smsUserService.querySmsUserListByIds(ids);
            final Map<Integer, List<SmsUser>> userMap = smsUsers.stream().collect(Collectors.groupingBy(SmsUser::getUserId));

            final List<ProjectMemberDTO> ProjectMemberDTOList = smsProjectMembers.stream()
                    .map(rs -> {
                        ProjectMemberDTO projectMemberDTO = new ProjectMemberDTO();
                        BeanUtils.copyProperties(rs, projectMemberDTO);
                        if (CollectionUtils.isNotEmpty(userMap.get(rs.getUserId()))) {
                            final SmsUser smsUser = userMap.get(rs.getUserId()).get(0);
                            projectMemberDTO.setUsername(StringUtils.isNotEmpty(smsUser.getUsername()) ? smsUser.getUsername() : "");
                        }
                        return projectMemberDTO;
                    }).collect(Collectors.toList());

            return ProjectMemberDTOList;

        }
        return null;
    }

    @Override
    public SmsProject querySmsProjectInfo(String smsProjectName, String token, String password) {
        return lambdaQuery()
                .eq(StringUtils.isNotEmpty(smsProjectName), SmsProject::getSmsProjectName, smsProjectName)
                .eq(StringUtils.isNotEmpty(token), SmsProject::getToken, token)
                .eq(StringUtils.isNotEmpty(password), SmsProject::getPassword, password)
                .one();
    }
}
